package com.data.app.dao.primary.impl;

import com.data.app.commons.utils.PinyinUtils;
import com.data.app.dao.primary.YhDisasterDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Repository
public class YhDisasterDaoImpl<T> implements YhDisasterDao<T> {
    @PersistenceContext
    private EntityManager em;
    @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:500}")
    private int BATCH_SIZE;

    @Override
    @Transactional
    public <S extends T> Iterable<S> batchSave(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            try {
                em.persist(iterator.next());
                //em.merge(iterator.next());
                index++;
                if (index % BATCH_SIZE == 0) {
                    em.flush();
                    em.clear();
                    System.out.println(index);
                }
            } catch (Exception e) {
                e.printStackTrace();
                //System.out.println("======插入出错的元素"+index+": " + iterator.next().toString());
            }
        }
        if (index % BATCH_SIZE != 0) {
            em.flush();
            em.clear();
        }
        return var1;
    }
    /**
     * 获取各省表的后缀
     */
    private String buildProvinceSubfix(String province) {
        String pinyinOfProvince = "";
        if (StringUtils.isNotBlank(province)) {
            pinyinOfProvince = PinyinUtils.getPinyin(province);
            if ("山西省".equals(province)) {
                pinyinOfProvince = (pinyinOfProvince + "1");
            } else if ("重庆市".equals(province)) {
                pinyinOfProvince = "chongqingshi";
            }
            pinyinOfProvince = ("_" + pinyinOfProvince);
        }
        return pinyinOfProvince;
    }
    @Override
    public List<Object[]> findYhCodeAndYhProjectTypeByIsValid(String province){
        //SELECT yh_code,yh_project_type FROM yh_disaster WHERE is_valid='1'
        String provinceSubfix = buildProvinceSubfix(province);
        StringBuilder sql = new StringBuilder("select yh_code,yh_project_type from yh_disaster" + provinceSubfix);
        StringBuilder whereSql = new StringBuilder(" where is_valid='1'");
        whereSql.append(" and extends1='C'");
        whereSql.append(" and create_time>'2022-08-10'");
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString());
        return query.getResultList();
    };
}
